// 当前用户ID（实际应从session或cookie获取）
    let currentUserId = 1;
    
    // 页面加载时获取收藏数据
    $(document).ready(function() {
        loadCollections();
        
        // 取消收藏事件
        $(document).on('click', '.btn-outline-danger', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const item = $(this).closest('.collection-item');
            const goodsId = item.attr('data-id');
            
            $.ajax({
                url: 'CollectionServlet',
                type: 'POST',
                data: {
                    action: 'deleteCollection',
                    userId: currentUserId,
                    goodsId: goodsId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.code === 200) {
                        // 添加删除动画效果
                        item.css({
                            'opacity': 0.5,
                            'background': '#ffe6e6',
                            'transition': 'all 0.3s ease'
                        });
                        setTimeout(() => {
                            item.fadeOut(300, function() {
                                $(this).remove();
                                // 检查是否还有收藏项
                                if ($('.collection-item').length === 0) {
                                    $('.collection-container').html(
                                        '<div class="text-center py-5">' +
                                        '<i class="fas fa-heart-broken fa-3x mb-3"></i>' +
                                        '<p class="fs-5">暂无收藏的商品</p>' +
                                        '</div>'
                                    );
                                }
                            });
                        }, 500);
                    } else {
                        showToast('操作失败: ' + response.msg, 'error');
                    }
                },
                error: function() {
                    showToast('操作失败，请稍后重试', 'error');
                }
            });
        });
    });
    
    // 加载收藏数据
    function loadCollections() {
        $.ajax({
            url: 'CollectionServlet',
            type: 'POST',
            data: {
                action: 'getCollections',
                userId: currentUserId
            },
            dataType: 'json',
            beforeSend: function() {
                // 显示加载动画
                $('.collection-container').html(
                    '<div class="text-center py-5">' +
                    '<i class="fas fa-spinner fa-spin fa-3x"></i>' +
                    '<p class="mt-3">正在加载收藏列表...</p>' +
                    '</div>'
                );
            },
            success: function(response) {
                if (response.code === 200) {
                    if (response.data.length > 0) {
                        renderCollections(response.data);
                    } else {
                        $('.collection-container').html(
                            '<div class="text-center py-5">' +
                            '<i class="fas fa-heart-broken fa-3x mb-3"></i>' +
                            '<p class="fs-5">暂无收藏的商品</p>' +
                            '<p class="text-muted">快去浏览商品添加收藏吧</p>' +
                            '</div>'
                        );
                    }
                } else {
                    $('.collection-container').html(
                        '<div class="text-center py-5">' +
                        '<i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>' +
                        '<p class="fs-5">加载失败: ' + response.msg + '</p>' +
                        '<button class="btn btn-primary mt-2" onclick="loadCollections()">重新加载</button>' +
                        '</div>'
                    );
                }
            },
            error: function() {
                $('.collection-container').html(
                    '<div class="text-center py-5">' +
                    '<i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>' +
                    '<p class="fs-5">网络请求失败，请检查网络连接</p>' +
                    '<button class="btn btn-primary mt-2" onclick="loadCollections()">重新加载</button>' +
                    '</div>'
                );
            }
        });
    }
    
    // 渲染收藏列表
    function renderCollections(collections) {
        let html = '';
        
        collections.forEach(function(item) {
        	console.log(item)
            html += `
            <form action="goodsInfo">
            	<a href="#" onclick="$(this).parent().submit();">
            	<input type="hidden" name="goodId" value="${item.goodid }">
    			<input type="hidden" name="userId" value="${item.sellerId }">
                <div class="collection-item" data-id="${item.goodid}">
                    <div class="collection-badge">${getConditionText(item.goodstat)}</div>
                    <div class="collection-img-container">
                        <img src="${item.goodimg || 'img/default-product.png'}" alt="${item.goodname}" class="collection-img">
                    </div>
                    <div class="collection-content">
                        <h3 class="collection-title">${item.goodname}</h3>
                        <div class="collection-price">¥ ${item.goodprice.toFixed(2)}</div>
                        <div class="collection-meta">
                            <span>收藏时间: ${formatDate(item.collectionTime)}</span>
                            <span><i class="fas fa-eye"></i> ${getRandomViewCount()}</span>
                        </div>
                        <div class="collection-actions">
                            <button type="button" class="btn btn-outline-danger btn-collection">
                                <i class="fas fa-trash-alt"></i> 取消收藏
                            </button>
                            <button type="button" class="btn btn-primary btn-collection">
                                <i class="fas fa-shopping-cart"></i> 立即购买
                            </button>
                        </div>
                    </div>
                </div>
                </a>
                </form>
            `;
        });
        
        $('.collection-container').html(html);
    }
    
    // 辅助函数：格式化日期
    function formatDate(date) {
        if (!date) return '未知时间';
        const d = new Date(date);
        return `${d.getFullYear()}-${padZero(d.getMonth() + 1)}-${padZero(d.getDate())}`;
    }
    
    // 辅助函数：补零
    function padZero(num) {
        return num < 10 ? `0${num}` : num;
    }
    
    // 辅助函数：获取商品状态文本
    function getConditionText(stat) {
        const conditions = {
            1: '全新',
            2: '99新',
            3: '95新',
            4: '9成新',
            5: '85新',
            6: '8成新',
            7: '7成新'
        };
        return conditions[stat] || conditions[0];
    }
    
    // 辅助函数：生成随机浏览量
    function getRandomViewCount() {
        const count = Math.floor(Math.random() * 5000) + 100;
        return count > 1000 ? `${(count / 1000).toFixed(1)}K` : count;
    }
    
    // 显示Toast提示
    function showToast(message, type = 'success') {
        // 这里实现您的toast提示功能
        alert(message); // 简化实现，实际应用中应使用toast组件
    }